package top.lcm889.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Coder-lcm
 * @date 2021/3/8
 */
public class MyExecutors {
    //线程池中的线程
    private List<WorkThread> workThreads;
    //线程任务队列
    private LinkedBlockingDeque<Runnable> runnables;
    private boolean isRun = true;

    public MyExecutors(int maxThreadNum, int dequeSize){
        runnables = new LinkedBlockingDeque<Runnable>(dequeSize);
        workThreads = new ArrayList<WorkThread>(maxThreadNum);
        for (int i = 0; i < maxThreadNum; i++) {
            new WorkThread().start();
        }
    }

    class WorkThread extends Thread{
        @Override
        public void run() {
            while (isRun || runnables.size() > 0){
                Runnable runnable = runnables.poll();
                if (runnable != null){
                    runnable.run();
                }
            }
        }
    }

    public boolean execute(Runnable command){
        return runnables.offer(command);
    }

    public static void main(String[] args) {
        MyExecutors myExecutors = new MyExecutors(9, 20);
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            myExecutors.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ", " + finalI + " " + System.currentTimeMillis());
                }
            });
        }
        myExecutors.isRun = false;
    }
}
